//
//  JCWLogInPswVC.swift
//  HengYouCai
//
//  Created by wll on 2017/12/27.
//  Copyright © 2017年 lwj. All rights reserved.
//  登录界面--代码  输入登录密码

import UIKit


class JCWLogInPswVC: BaseViewController {

    ///手机号 
    var phoneNumber: String?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.createNav()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //取消导航栏透明
//        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
//        self.navigationController?.navigationBar.shadowImage = nil
//        // 状态栏 字体黑色
////        UIApplication.shared.statusBarStyle = .default
//        //不影响找回登录密码界面标题颜色
////        self.wl_navTitle("", titleColor: UIColor.black)
//        self.navigationController?.navigationBar.subviews.first?.alpha = 1
    }
    
    deinit {
        debugPrint("JCWLogInPswVC dealloc")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCV()
        self.pswView.tF.becomeFirstResponder()
    }
    
    func createNav() {
//        self.navigationController?.navigationBar.tintColor = UIColor.white
       
        self.navigationController?.navigationBar.setBackgroundImage( UIImage(named: "touming"), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
        self.wl_navTitle("登录", titleColor: UIColor.white)
        //蛋疼的布局循环 bug 导致 颜色刷新不执行
        let titleLab = UILabel(frame: CGRect.zero)
        titleLab.textColor = UIColor.white
        titleLab.text = "登录"
        titleLab.sizeToFit()
        self.navigationItem.titleView = titleLab
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: Image(named: "back_white"),
                                                                style: .done,
                                                                target: self,
                                                                action: #selector(leftBarButtonItemClick))
        self.navigationController?.navigationBar.subviews.first?.alpha = 0
        
    }
    func createCV() {
        
        self.view.backgroundColor = UIColor.white
        
        self.view.addSubview(self.topBgImV)
        self.topBgImV.frame = CGRect(x: 0, y: 0, width: self.view.width_sd, height: self.view.width_sd*self.topBgImV.height_sd/self.topBgImV.width_sd)
        
        self.view.addSubview(self.pswView)
        self.pswView.center = self.view.center
        self.pswView.bounds = CGRect(x: 0, y: 0, width: self.view.width_sd-JCWLogRegTFMargin*2, height: JCWLogRegTFH)
        self.pswView.bottom_sd = self.topBgImV.bottom_sd - 86.aw_wl
        
        self.view.addSubview(self.logoImV)
        self.logoImV.centerX_sd = self.view.centerX_sd
        self.logoImV.bottom_sd = self.pswView.top_sd - 60
        
        self.view.addSubview(self.logInBtn)
        self.logInBtn.frame = CGRect(x: JCWLogRegTFMargin, y: self.topBgImV.bottom_sd+100.aw_wl, width: self.pswView.width_sd, height: 44)
        self.view.addSubview(self.forgetPswBtn)
        self.forgetPswBtn.top_sd = self.pswView.bottom_sd+5
        self.forgetPswBtn.right_sd = self.pswView.right_sd
        
        
        //监控按钮状态
        weak var weakSelf = self
        self.pswView.tF.reactive.continuousTextValues.observeValues { (text) in
            weakSelf?.logInBtn.isUserInteractionEnabled = !text!.isEmpty
            weakSelf?.logInBtn.setBackgroundImage(UIImage(named: text!.isEmpty ?"login_btn_gray":"login_btn"), for: .normal)
        }
        
    }
    //MARK:按钮点击事件
    @objc fileprivate func leftBarButtonItemClick(){
        self.navigationController?.popViewController(animated: true);
    }
    //登录事件
    @objc fileprivate func logInBtnClick() {
        self.loadData()
    }
    //忘记密码事件
    @objc fileprivate func forgetPswBtnClick() {
        let getPswVC = GetBackLoginPswVC()
        getPswVC.phoneNumber = phoneNumber!
        self.pushVC(getPswVC)
    }
    
    //MARK:懒加载UI
    ///大背景
    fileprivate lazy var topBgImV: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "login_bg"))
        temp.sizeToFit()
        return temp
    }()
    ///logo
    fileprivate lazy var logoImV: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "login_logo"))
        temp.sizeToFit()
        temp.isHidden = true
        return temp
    }()
    ///密码输入框
    fileprivate lazy var pswView: JCWAlertTextFieldView = {
        let temp = JCWAlertTextFieldView("请输入登录密码", "请输入登录密码", "login_password")
        temp.tF.isSecureTextEntry = true
        return temp
    }()
    ///登录按钮
    fileprivate lazy var logInBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setBackgroundImage(UIImage(named: "login_btn_gray"), for: .normal)
        temp.isUserInteractionEnabled = false
        temp.adjustsImageWhenHighlighted = false
        temp.setTitle("登录", for: .normal)
        temp.titleLabel?.font = Font_WL(15)
        temp.addTarget(self, action: #selector(logInBtnClick), for: .touchUpInside)
        return temp
    }()
    ///忘记密码按钮
    fileprivate lazy var forgetPswBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.adjustsImageWhenHighlighted = false
        temp.setTitle("忘记密码?", for: .normal)
        temp.titleLabel?.font = Font_WL(14)
//        temp.setTitleColor(Normal_BlueColor, for: .normal)
        temp.addTarget(self, action: #selector(forgetPswBtnClick), for: .touchUpInside)
        temp.sizeToFit()
        return temp
    }()

}

extension JCWLogInPswVC {
    fileprivate func loadData() {
        self.view.jcw_showGifLoading()
        //登录
       
        HYCNetService.login(withDict: ["userAccount":self.phoneNumber ?? "","passwd":self.pswView.tF.text ?? "","token":WLFileManager.readUserData(forKey: "GetuiClientId")], onSuccess: { (result) in
            //登录成功缓存sessionId
            WLFileManager.saveUserData(result?["sessionId"], forKey: kUserSessionId)
            //登陆成功获取用户信息
            HYCNetService.getUserInfoSuccess({ (resultDic) in
                self.view.hideHUDLoading(0)
                //缓存用户信息
                let dic: Dictionary? = resultDic?["result"] as? Dictionary<String,Any>
                WLFileManager.saveUserData(dic?["cusCode"], forKey: kCusCode)
                WLFileManager.saveUserData(dic?["cardStatus"], forKey: kCardStatus)
                WLFileManager.saveUserData(dic?["userIdCard"], forKey: kUserIdCard)
                WLFileManager.saveUserData(dic?["userRealname"], forKey: kUserRealname)
                WLFileManager.saveUserData(dic?["userPaypassword"], forKey: kUserPaypassword)
                WLFileManager.saveUserData(dic?["realnameStatus"], forKey: kRealnameStatus)
                WLFileManager.saveUserData(dic?["userAccount"], forKey: kUserAccount)
                WLFileManager.saveUserData(dic?["userLevel"], forKey: kUserLevel)
                self.dismissVC()
            }, andFailed: { (c, e) in
                //获取用户信息失败
                self.view.showHUDFailTips(e, hideDelay: kHUDHideDelay)
            })
        }, andFailed: { (code, errorMsg) in
            //登录失败
            self.view.showHUDFailTips(errorMsg, hideDelay: kHUDHideDelay)
        })
    }
}
